const express = require('express'); const app = express(); const PORT = 3000; ... app.listen(PORT, function (err) { if (err) console.log(err); console.log("Server listening on PORT", PORT); });
app.use(...); // E.g., // app.use(express.urlencoded({ extended: false })); // for the POST query data // From Github: The "extended" syntax allows for rich objects and arrays to be encoded into the URL-encoded format, allowing for a JSON-like experience with URL-encoded. // app.use(express.json());
// Allow Cross-domain requests, i.e., CORS // Why do we need this? app.all('/*', function(req, res, next) { // all(): any HTTP method; /*: any path res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); // Default: only GET and POST next(); // Express middleware function; To continue to next operations });
// get, post, put, delete, ..., all // E.g., app.post("/echo", function(req, res) { ... }); // E.g., app.get("/calculator/adder", function(req, res) { ... }); // req and res objects are different from those used in http.createServer(). app.methodname(path, (req, res) => { ... res.send(...); }) // path could be "*" get.all(path, (req, res) => { ... res.send(...); })
Connect to cs.tru.ca with your account, save the above code in hello_express.js, and complete and run it.
You can test your express server from a web browser.
(Note that if you did not install the 'express' module, then install it. $ npm install express
)
app.get(path, (req, res) => { ... req.query.queryname ... });
app.use(express.urlencoded({ extended: false })); app.methodname(path, (req, res) => { ... req.body.queryname ... });
res.send(message);
req
- the request object
res
- the response object
Connect to cs.tru.ca with your account, save the above code in echo_express.js, and complete and run it.
You can test your echo server with http://cs.tru.ca/~mlee/comp4620/Winter2025/5.%20back_end_technologies/echo_calculator_express.html
Anything wrong? The use of a different port number makes a web browser think that your server-side app is from a different origin.
Connect to cs.tru.ca with your account, save the above code in echo_express.js, and complete and run it.
You can test your echo server with http://cs.tru.ca/~mlee/comp4620/Winter2025/5.%20back_end_technologies/echo_calculator_express.html
Connect to cs.tru.ca with your account, save the above code in calculator_express.js, and complete and run it.
You can test your calculator server with http://cs.tru.ca/~mlee/comp4620/Winter2025/5.%20back_end_technologies/echo_calculator_express.html
Can you add more code to support other arithmetic operations?